package controller;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import model.GroupManager;
import model.Student;

@WebServlet("/AdminServlet")
public class AdminServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        GroupManager groupManager = (GroupManager) getServletContext().getAttribute("groupManager");
        request.setAttribute("groups", groupManager.getGroups());
        request.getRequestDispatcher("admin.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        GroupManager groupManager = (GroupManager) getServletContext().getAttribute("groupManager");
        String action = request.getParameter("action");

        if ("remove".equals(action)) {
            String studentId = request.getParameter("studentId");
            groupManager.removeStudentFromGroup(studentId);
        } else if ("add".equals(action)) {
            String name = request.getParameter("name").trim();
            String studentId = request.getParameter("studentId").trim();
            int groupNumber = Integer.parseInt(request.getParameter("groupNumber"));

            if (groupNumber < 1 || groupNumber > groupManager.TOTAL_GROUPS) {
                request.setAttribute("error", "分组编号无效！");
            } else if (groupManager.isValidStudent(name, studentId)) {
                if (!groupManager.isStudentGrouped(studentId)) {
                    Student student = new Student(name, studentId);
                    groupManager.addStudentToSpecificGroup(student, groupNumber);
                } else {
                    request.setAttribute("error", "该学生已在分组中！");
                }
            } else {
                request.setAttribute("error", "姓名或学号错误！");
            }
        } else if ("save".equals(action)) {
            groupManager.saveGroupResults();
        }

        request.setAttribute("groups", groupManager.getGroups());
        request.getRequestDispatcher("admin.jsp").forward(request, response);
    }
}
